//
//  CZOauthViewController.swift
//  swiftweibo1.0
//
//  Created by 许建安 on 15/11/26.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

import SVProgressHUD //SVProgressHUD 显示的框架

class CZOauthViewController: UIViewController {
    override func loadView() {
        //不用设置约束
        view = webView //设置Oauth的view为webView,webView懒加载的UIWebView()属性
//        webView.delegate = self
        
    }
    
    ///MARK: -懒加载
    //webView
    private lazy var webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载授权界面
        let request = NSURLRequest(URL: CZNetworkTool.sharedInstance.oauthURL())
        //利用请求加载登录页面
        webView.loadRequest(request)
        
        //设置导航栏
        //左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        //右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    //填充账户
    func autoFill() {
        //创建js代码
        let js = "document.getElementById('userId').value='aaqa856@163.com'; document.getElementById('passwd').value='asd8564647';"
        
        //让webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    //关闭控制器
    func close() {
        //关闭
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //加载accessToken
    func loadAccessToken(code: String)
    {
        //发送网络请求
        CZNetworkTool.sharedInstance.loadAccessToken(code) { (result, error) -> () in
            //判断是否有错误，有就提示用户，关闭控制器
            if error != nil || result == nil {
                //告诉用户出错了
                SVProgressHUD.showErrorWithStatus("你的网络不给力", maskType: SVProgressHUDMaskType.Black)
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.close()
                })
                return
            }
            //没有出错，保存数据
            //创建模型
            let userAccount = CZUserAccount(dict: result!)
            
            //保存对象
            userAccount.saveAccout()
            print("\(userAccount)")
        }
    }
}


//MARK: - 扩展 CZOauthViewCintroller 实现UIWebViewDelegate协议
extension CZOauthViewController: UIWebViewDelegate {
    ///webView开始加载链接
    func webViewDidStartLoad(webView: UIWebView) {
        //showWithStatus只要没有主动关闭，就会一直显示
        //showInfoWithStatus 过段时间就消失了
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Black)
    }
    
    //webView开始加载完成某个链接
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //webView加载链接，每加载一个就询问这个地址能否加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        
        //当用户点击取消或者同意时
        if !urlString.hasPrefix(CZNetworkTool.sharedInstance.redirect_uri) {
            return true
        }
        //判断url地址里面是以code=开头，截取code= 后面的字符串
        if let query = request.URL?.query {
            let codeString = "code="
            //判断是不是以code=开头
            if query.hasPrefix(codeString) {
                //点击授权，截取code的值
                let nsQuery = query as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                
                //加载accessToken
                loadAccessToken(code)
            } else {
                //点击取消
                print("点击取消")
                self.close()
            }
        }
        
        //不去加载授权回调地址
        return false
        
    }
    
}

    










